<?php

namespace app\service\admin\projects\shop;

use think\facade\Db;
use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * 商品管理
 * User : Du
 * Date : 2022/12/1
 * Time : 22:04
 * Class GoodsServices
 * @package projects\services\admin\shop
 */
class GoodsService
{

    /**
     * 商品所属分类
     * User : Du
     * Date : 2022/12/2
     * Time : 16:44
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getClassify(): array
    {
        return Common::getAllData(GoodsClassifyTable, [], ['id', 'name'], true);
    }

    /**
     * 列表数据
     * User : Du
     * Date : 2022/12/1
     * Time : 22:24
     * @param array $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(array $request): array
    {
        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $so = $request['so'] ?? '';
        $filter = [];
        if ($so) {
            $filter[] = ['name', 'like', '%' . $so . '%'];
        }
        $field = ['id', 'name', 'cover', 'create_time'];
        return Common::getList(GoodsInfoTable, $filter, $field, $page, $size);
    }

    /**
     * 添加商品
     * @param array $request
     * @return bool
     */
    public static function add(array $request): bool
    {
        $data = [
            'name' => $request['goods_name'],
            'classify_id' => $request['classify_id'],
            'status' => $request['status'] ?? 0,
            'cover' => $request['cover'],
            'weight' => $request['weight'],
            'postage' => $request['postage'] ?? 0,
            'details' => $request['details'],
        ];
        if (isset($request['show_picture']) && $request['show_picture'] !== '') {
            $data['show_picture'] = arrayToJson($request['show_picture']);
        }
        // 启动事务
        Db::startTrans();
        try {
            $id = Common::addData(GoodsInfoTable, $data, true);
            $list = [];
            foreach ($request['name'] as $k => $v) {
                $list[] = [
                    'goods_id' => $id,
                    'name' => $v,
                    'price' => $request['price'][$k],
                    'number' => $request['number'][$k],
                ];
            }
            Common::addAllData(GoodsSpecTable, $list);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    /**
     * 商品详情
     * @param array $request
     * @return array|false|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function info(array $request)
    {
        if (!isset($request['id']) || !$request['id']) {
            return false;
        }
        $field = ['id', 'name', 'classify_id', 'status', 'cover', 'weight', 'postage', 'show_picture', 'details'];
        $res = Common::getData(GoodsInfoTable, ['id' => $request['id']], $field);
        if (!$res) {
            return false;
        }
        $res['cover'] = imagePath($res['cover']);
        if ($res['show_picture']) {
            $res['show_picture'] = jsonToArray($res['show_picture']);
            foreach ($res['show_picture'] as &$v) {
                $v = imagePath($v);
            }
        }
        $field = ['id', 'goods_id', 'name', 'price', 'number'];
        $res['spec'] = Common::getAllData(GoodsSpecTable, ['goods_id' => $request['id']], $field)['data'];
        return $res;
    }

    /**
     * 修改商品
     * @param array $request
     * @return bool
     */
    public static function update(array $request): bool
    {
        if (!isset($request['id']) || !$request['id']) {
            return false;
        }
        $data = [
            'name' => $request['goods_name'],
            'classify_id' => $request['classify_id'],
            'status' => $request['status'] ?? 0,
            'weight' => $request['weight'],
            'postage' => $request['postage'] ?? 0,
            'details' => $request['details'],
        ];
        if ($request['cover']) {
            $data['cover'] = $request['cover'];
        }
        if ($request['show_picture']) {
            $data['show_picture'] = arrayToJson($request['show_picture']);
        }
        // 启动事务
        Db::startTrans();
        try {
            Common::updateData(GoodsInfoTable, ['id' => $request['id']], $data);
            $list = [];
            foreach ($request['name'] as $k => $v) {
                $list[] = [
                    'goods_id' => $request['id'],
                    'name' => $v,
                    'price' => $request['price'][$k],
                    'number' => $request['number'][$k],
                ];
            }
            Common::deleteData(GoodsSpecTable, ['goods_id' => $request['id']], true);
            Common::addAllData(GoodsSpecTable, $list);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }

    }

    /**
     * 删除商品
     * @param array $request
     * @return bool
     */
    public static function delete(array $request): bool
    {
        if (!isset($request['data']) || !$request['data']) {
            return false;
        }
        $list = [];
        foreach ($request['data'] as $v) {
            $list[] = $v['id'];
        }
        if (!$list) {
            return false;
        }
        Db::startTrans();
        try {
            Common::deleteData(GoodsInfoTable, ['id' => $list]);
            Common::deleteData(GoodsSpecTable, ['goods_id' => $list]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
}